<template>
  <div class="oe-exam-list" v-loading="loading">
    <top-tip :title="titleList" :showBack="false"></top-tip>
      <div class="oe-examlist-input">
        批次名称：
        <a-input v-model="examName" placeholder="请输入批次名称" @keyup.13="getExamList" />
        <span class="oe-manage-text">&nbsp;&nbsp;&nbsp;&nbsp;系统类型：</span>
        <span class="oe-manage-select">
          <a-select v-model="selectChooseType" style="width: 120px">
            <a-select-option value="全部">全部</a-select-option>
            <a-select-option value="0">考核系统</a-select-option>
            <!-- <a-select-option value="1">练习系统</a-select-option> -->
            <a-select-option value="2">组卷系统</a-select-option>
          </a-select>
        </span> 
        <a-button type="primary" @click.stop="getExamList()">查询</a-button>
        <a-button
          type="primary"
          @click="clickAction('新增')"
          v-if="operationList.includes('add/edit/del')"
        >新增</a-button>
      </div>
    <div class="oe-examlist-contianer">
    
      <div class="oe-examlist-table">
        <a-table
          :columns="columns"
          :dataSource="dataList"
          :pagination="pagination"
          @change="onTableChange"
        >
          <span slot="operation" slot-scope="text, record" >
            <a-tooltip placement="bottom">
              <template slot="title">
                <span>考试管理</span>
              </template>
              <span
                class="oe-table-delete iconfont icon-jinru"
                @click.stop="clickAction('查看', record)"
              ></span>
            </a-tooltip>
            <a-tooltip placement="bottom">
              <template slot="title">
                <span>编辑</span>
              </template>
              <span
                class="oe-table-delete iconfont icon-edit"
                v-if="operationList.includes('add/edit/del')"
                @click.stop="clickAction('编辑', record)"
              ></span>
            </a-tooltip>
            <a-tooltip placement="bottom">
              <template slot="title">
                <span>删除</span>
              </template>
              <span
                class="oe-table-delete iconfont icon-delete"
                v-if="operationList.includes('add/edit/del')"
                @click.stop="clickAction('删除', record)"
              ></span>
            </a-tooltip>
          </span>
        </a-table>
      </div>
    </div>
    <a-modal :title="modalTitle" class="oe-list-modal" centered v-model="visible">
      <div class="oe-list-line">
        <a-button
          :class="sysType === 0 ? 'sysType-div-choose' : 'sysType-div' "
          @click.stop="checkType(0)"
        >考核系统</a-button>
        <!-- <a-button
          :class="sysType === 1 ? 'sysType-div-choose' : 'sysType-div' "
          @click.stop="checkType(1)"
        >练习系统</a-button> -->
        <a-button
          :class="sysType === 2 ? 'sysType-div-choose' : 'sysType-div' "
          @click.stop="checkType(2)"
        >组卷系统</a-button>
      </div>
      <div class="oe-list-line">
        <span class="oe-title-text">批次名称：</span>
        <a-input v-model="countName" placeholder="请填写批次名称"></a-input>
      </div>
      <div class="oe-list-line">
        <span class="oe-title-text">负责人：</span>
        <a-select
          v-model="userId"
          style="width:300px"
          showSearch
          @change="Changesub"
          :allowClear="true"
          optionFilterProp="children"
          placeholder="请选择负责人"
        >
          <a-select-option
            v-for="item in teacherList"
            :value="item.id"
            :key="item.id"
            with="100%"
          >{{ item.text }}</a-select-option>
        </a-select>
      </div>
      <div class="oe-list-line" v-show="sysType === 0">
        <span class="oe-title-text">巡考人：</span>
        <a-select
          v-model="inspectionId"
          style="width:300px"
          showSearch
          @change="ChangeXK"
          :allowClear="true"
          optionFilterProp="children"
          placeholder="请选择巡考人"
        >
          <a-select-option
            v-for="item in teacherList"
            :value="item.id"
            :key="item.id"
            with="100%"
          >{{ item.text }}</a-select-option>
        </a-select>
      </div>
      <div class="oe-list-line">
        <span class="oe-title-text">开始时间：</span>
        <a-date-picker
          :disabledDate="disabledStartDate"
          showTime
          format="YYYY-MM-DD HH:mm:ss"
          v-model="startValue"
          placeholder="请输入开始时间"
          @openChange="handleStartOpenChange"
        />
      </div>
      <div class="oe-list-line">
        <span class="oe-title-text">结束时间：</span>
        <a-date-picker
          :disabledDate="disabledEndDate"
          showTime
          format="YYYY-MM-DD HH:mm:ss"
          placeholder="请输入结束时间"
          v-model="endValue"
          :open="endOpen"
          @openChange="handleEndOpenChange"
        />
      </div>
      <div class="oe-list-line" v-show="sysType != 2">
        <span class="oe-title-text">学校名称：</span>
        <a-select
          mode="multiple"
          style="width:300px"
          showSearch
          :allowClear="true"
          v-model="CreateName"
          optionFilterProp="children"
          @change="selectTeacher"
          placeholder="请输入学校名称查询"
        >
          <a-select-option v-for="item in selection" :index="index" :key="item.id">{{ item.text }}</a-select-option>
        </a-select>
      </div>
      <div class="oe-list-line" v-show="sysType === 0">
        <span class="oe-title-text">考试方式：</span>
        <a-checkbox style="width:100px" value="onlineExam" v-model="onlineExam">线上考试</a-checkbox>
        <a-checkbox style="width:200px" value="outlineExam" v-model="outlineExam">线下考试</a-checkbox>
      </div>
      <div slot="footer">
        <a-button type="primary" @click.stop="saveAction">确认</a-button>
        <a-button @click.stop="visible = false">取消</a-button>
      </div>
    </a-modal>
  </div>
</template>

<script>
import topTip from '@/components/top-tip/index.vue';
import GetOperationList from '@/lib/mixin/methods.js';
export default {
  name: 'examList',
  mixins: [GetOperationList],
  components: {
    topTip
  },
  data() {
    return {
      CreateName: [],
      selection: [],
      mainTeacherIds: [],
      onlineExam: true,
      outlineExam: false,
      titleList: [{ text: '批次(考试)管理' }],
      examName: '',
      // 分页配置
      pagination: {
        pageSizeOptions: ['10', '20', '50', '100', '1000'],
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal(total) {
          return `共 ${total} 条`;
        },
        onShowSizeChange: (current, pageSize) => {
          this.pagination.current = current;
          this.pagination.pageSize = pageSize;
        },
        onChange: (current, pageSize) => {
          // this.getExamList(current, pageSize);
          this.pagination.current = current;
          this.pagination.pageSize = pageSize;
        },
        buildOptionText(props) {
          // console.log(props);
          return props.value + '条/页';
        },
        current: 1,
        pageSize: 10,
        total: 0
      },
      // 表标题
      columns: [
        {
          title: '序号',
          dataIndex: 'Number',
          width: '5%',
          key: 'Number'
        },
        {
          title: '批次名称',
          dataIndex: 'Title',
          width: '13%',
          key: 'Title',
          sorter: true
        },
        {
          title: '系统类型',
          dataIndex: 'SysType',
          width: '8%',
          key: 'SysType',
          sorter: true
        },
        {
          title: '负责人',
          dataIndex: 'DisplayName',
          width: '8%',
          key: 'DisplayName',
          sorter: true
        },
        {
          title: '巡考人',
          dataIndex: 'InspectionName',
          width: '8%',
          key: 'InspectionName',
          sorter: true
        },
        {
          title: '开始时间',
          dataIndex: 'StartTime',
          width: '10%',
          key: 'StartTime',
          sorter: true
        },
        {
          title: '结束时间',
          dataIndex: 'EndTime',
          width: '10%',
          key: 'EndTime',
          sorter: true
        },
        {
          title: '考试方式',
          dataIndex: 'ExamMode',
          width: '10%',
          key: 'ExamMode',
          sorter: true
        },
        {
          title: '创建人',
          dataIndex: 'CreatorName',
          width: '8%',
          key: 'CreatorName',
          sorter: true
        },
        {
          title: '创建时间',
          dataIndex: 'DateCreated',
          width: '10%',
          key: 'DateCreated',
          sorter: true
        },
        {
          title: '操作',
          dataIndex: 'operation',
          width: '10%',
          key: 'operation',
          align:'center',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      // 数据列表
      dataList: [],
      // modal是否可见
      visible: false,
      // modal的title
      modalTitle: '新增批次',
      // 批次名称
      countName: '',
      userId: undefined,
      inspectionId: undefined,
      teacherList: [],
      // 开始时间
      startValue: null,
      // 结束时间
      endValue: null,
      endOpen: false,
      // 数据加载
      loading: false,
      // 点击插卡你的ittem
      lookItem: '',
      // 操作List
      operationList: [],
      // 、操作list
      IsOpList: [],
      sysType: 0,
      selectChooseType: '全部'
    };
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.getOpeartion();
    });
  },
  methods: {
    // //搜索多选
    selectTeacher(val) {
      this.mainTeacherIds = val;
      // console.log('main', this.mainTeacherIds);
    },
    //获取学校列表
    getRoleList() {
      this.$http
        .post('/api/common/localstorage/getESSchoolList', {
          q: this.selected
        })
        .then((res) => {
          this.selection = res.list;
        });
    },
    // 获取页面操作
    getOpeartion() {
      this.loading = true;
      this.GetOperationList().then((rst) => {
        this.loading = false;
        this.operationList = [];
        this.IsOpList = [];
        if (rst.code === 1) {
          if (rst.list.length) {
            rst.list.forEach((item) => {
              if (item.IsWrite) {
                this.operationList.push(item.Name);
              }
            });
            this.IsOpList = rst.list;
            // this.operationList = rst.list;
          }
          this.getExamList();
          this.getTeacherList();
          this.getRoleList();
        } else {
          this.$message.error(rst.msg);
        }
      });
    },
    // 点击table排序
    onTableChange(pagenation, filter, sort) {
      let sortOrder = '';
      console.log(sort.columnKey);
      if (sort.order) {
        if (sort.order == 'ascend') {
          sortOrder = sort.columnKey;
        } else if (sort.order == 'descend') {
          sortOrder = '-' + sort.columnKey;
        } else {
          sortOrder = '';
        }
      }
      this.getExamList(pagenation.current, pagenation.pageSize, sortOrder);
    },
    // 获取考试列表
    getExamList(page, pageSize, sortOrder) {
      this.loading = true;
      this.$http
        .post('/api/design/batch/getList', {
          key: this.examName,
          selectChooseType: this.selectChooseType == '全部' ? '' : this.selectChooseType,
          sort: sortOrder || '',
          page: page || 1,
          pageSize: pageSize || 10
        })
        .then((rst) => {
          this.loading = false;
          if (rst.code == 1) {
            this.dataList = [];
            this.pagination.current = rst.pagination.pageIndex;
            this.pagination.pageSize = rst.pagination.pageSize;
            this.pagination.total = rst.pagination.totalCount;
            if (rst.list.length) {
              rst.list.forEach((item, index) => {
                let number = (rst.pagination.pageIndex - 1) * rst.pagination.pageSize + index + 1;
                this.dataList.push({
                  ...item,
                  Number: number
                });
              });
            }
          } else {
            this.$message.error(rst.msg);
          }
        });
    },
    // 点击操作
    clickAction(type, data) {
      let index = this.IsOpList.findIndex((el) => {
        return el.Name === type;
      });
      if (index > -1) {
        // this.IsOpList[index].IsRead
        if (this.IsOpList[index].IsRead && !this.IsOpList[index].IsWrite) {
          this.$message.info('您没有该操作权限，请先进行添加！');
          return;
        }
      }
      switch (type) {
        case '查看':
          this.$router.push({
            name: 'examManagement',
            params: {
              batchid: data.Id
            }
          });
          break;
        case '编辑':
          this.modalTitle = '编辑批次';
          this.lookItem = data;
          this.countName = data.Title;
          this.startValue = this.$moment(data.StartTime, 'YYYY-MM-DD HH:mm:ss');
          this.endValue = this.$moment(data.EndTime, 'YYYY-MM-DD HH:mm:ss');
          this.userId = data.UserId;
          this.inspectionId = data.InspectionId;
          this.$http
            .post('/api/design/batch/getInfo', {
              id: data.Id
            })
            .then((res) => {
              if (res.code > 0) {
                this.onlineExam = res.batchInfo.ExamMode == 2 || res.batchInfo.ExamMode == 0;
                this.outlineExam = res.batchInfo.ExamMode == 2 || res.batchInfo.ExamMode == 1;
                this.sysType = res.batchInfo.SysType;
                this.CreateName = [];
                this.mainTeacherIds = [];
                res.schoolList.forEach((item) => {
                  let index = this.selection.findIndex((school) => {
                    return school.id === item.Id;
                  });
                  if (index > -1) {
                    this.CreateName.push(this.selection[index].id);
                    this.mainTeacherIds.push(this.selection[index].id);
                  }
                });
              } else {
                this.$message.error(res.msg);
              }
            });
          this.visible = true;
          break;
        case '删除':
          this.$confirm({
            title: '提示',
            content: '你确定要删除该批次吗？',
            centered: true,
            onOk: () => {
              this.loading = true;
              this.$http
                .post('/api/design/batch/change', {
                  id: data.Id
                })
                .then((rst) => {
                  this.loading = false;
                  if (rst.code === 1) {
                    this.$message.success(rst.msg);
                    this.getExamList();
                  } else {
                    this.$message.error(rst.msg);
                  }
                });
            },
            onCancel() {}
          });
          break;
        case '新增':
          this.sysType = 0;
          this.countName = '';
          this.startValue = null;
          this.endValue = null;
          this.modalTitle = '新增批次';
          this.visible = true;
          this.CreateName = localStorage.getItem('schoolId') ? [localStorage.getItem('schoolId')] : [];
          this.userId = undefined;
          this.inspectionId = undefined;
          this.onlineExam = true;
          this.outlineExam = false;
          break;
        default:
          break;
      }
    },
    // 编辑或新增
    saveAction() {
      let id = this.modalTitle === '编辑批次' ? this.lookItem.Id : '';
      if (!this.startValue || !this.endValue || !this.countName || !this.CreateName) {
        this.$message.error('请将信息填写完整');
        return;
      }
      if (!this.onlineExam && !this.outlineExam && this.sysType == 0) {
        this.$message.error('至少选择一个考试方式');
        return;
      }
      // this.loading = true;
      let examMode = 0;
      if (this.outlineExam && this.onlineExam) {
        examMode = 2;
      } else if (this.outlineExam) {
        examMode = 1;
      } else if (this.onlineExam) {
        examMode = 0;
      }
      this.$http
        .post('/api/design/batch/save', {
          id,
          userId: this.userId,
          inspectionId: this.inspectionId,
          title: this.countName,
          startTime: this.$moment(this.startValue).format('YYYY-MM-DD HH:mm:ss'),
          endTime: this.$moment(this.endValue).format('YYYY-MM-DD HH:mm:ss'),
          schoolIds: this.mainTeacherIds,
          examMode: examMode,
          sysType: this.sysType
        })
        .then((rst) => {
          this.loading = false;
          if (rst.code === 1) {
            this.lookItem = '';
            this.visible = false;
            this.CreateName = '';
            let msg = this.modalTitle === '编辑批次' ? '修改成功' : '新增成功';
            this.$message.success(msg);
            this.countName = '';
            this.startValue = null;
            this.endValue = null;
            this.mainTeacherIds = [];
            this.getExamList();
          } else {
            this.$message.error(rst.msg);
          }
        });
    },
    //获取责任教师
    getTeacherList(val) {
      this.fetching = true;
      this.$http
        .post('/api/design/workexam/getDutyTea', {
          q: val ? val : ''
        })
        .then((rst) => {
          this.fetching = false;
          this.teacherList = [];
          if (rst.code == 1) {
            this.teacherList = rst.list;
          } else {
            this.$message.error(rst.msg);
          }
        });
    },
    disabledStartDate(startValue) {
      const endValue = this.endValue;
      if (!startValue || !endValue) {
        return false;
      }
      return startValue.valueOf() > endValue.valueOf();
    },
    disabledEndDate(endValue) {
      const startValue = this.startValue;
      if (!endValue || !startValue) {
        return false;
      }
      return startValue.valueOf() >= endValue.valueOf();
    },
    handleStartOpenChange(open) {
      if (!open) {
        this.endOpen = true;
      }
    },
    handleEndOpenChange(open) {
      this.endOpen = open;
    },
    Changesub(value) {
      this.userId = value;
    },
    ChangeXK(value) {
      this.inspectionId = value;
    },
    checkType(val) {
      this.sysType = val;
    }
  }
};
</script>
